package com.example.jobback.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.example.jobback.config.AliyunConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: STSUtil
 * @Description: STSToken工具类
 * @Author: lhb
 * @Date: 2025/5/10
 */

public class STSUtil {
    public static Logger logger = LoggerFactory.getLogger(STSUtil.class);
    public static final String ACCESS_KEY_ID = "ACCESS_KEY_ID";
    public static final String ACCESS_KEY_SECRET = "ACCESS_KEY_SECRET";
    public static final String SECURITY_TOKEN = "SECURITY_TOKEN";
    public static final String EXPIRATION = "EXPIRATION";
    private static final String REGION = "cn-hangzhou";
    private static final String STS_API_VERSION = "2015-04-01";
    private static final String USER_ID="USER_ID";

    //这里的userName只是此次对话的名字而已
    public static JSONObject getCredit(Long userId, String userName, AliyunConfig aliyunConfig) throws ClientException {
        // 用于阿里云后台审计使用的临时名称，可根据实际业务传输，具体内容不影响服务使用
        //运行时的策略权限，这里将权限放到了最大，可根据实际情况而定。在运行时，实际权限为这里设置的权限和第一步中角色配置的策略权限的交集

        //切记 临时凭证的权限不能超过角色已有的权限：即使你在动态策略中为临时凭证指定了某些操作，如果这些操作超出了角色本身允许的范围，那么这些操作仍然会被拒绝。
        //临时凭证的权限可以进一步限制角色的权限：你可以在动态策略中为临时凭证设置更严格的权限，从而进一步限制角色的访问范围。
        JSONObject policyObject = new JSONObject();
        policyObject.fluentPut("Version", "1");
        List<JSONObject> statements = new ArrayList<>();


        //**********************************
        //增加get和put权限重点！！！控制台授权也不定能用
        statements.add(new JSONObject().fluentPut("Effect", "Allow").fluentPut("Action", List.of("oss:PutObject")).fluentPut("Resource", Arrays.asList("acs:oss:*:*:" + aliyunConfig.getBucketName(), "acs:oss:*:*:" + aliyunConfig.getBucketName() + "/*")));
        statements.add(new JSONObject().fluentPut("Effect", "Allow").fluentPut("Action", List.of("oss:GetObject")).fluentPut("Resource", Arrays.asList("acs:oss:*:*:" + aliyunConfig.getBucketName(), "acs:oss:*:*:" + aliyunConfig.getBucketName() + "/*")));
        policyObject.fluentPut("Statement", statements);
        logger.info("ali policy：{}", policyObject);

        //执行角色授权
        IClientProfile profile = DefaultProfile.getProfile(REGION, aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        DefaultAcsClient client = new DefaultAcsClient(profile);
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion(STS_API_VERSION);
        request.setRoleArn(aliyunConfig.getRoleArn());
        request.setRoleSessionName(userName);
        request.setPolicy(policyObject.toJSONString());
        //临时授权有效实践,从900到3600
        request.setDurationSeconds(900L);
        final AssumeRoleResponse response = client.getAcsResponse(request);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put(ACCESS_KEY_ID, response.getCredentials().getAccessKeyId());
        jsonObject.put(ACCESS_KEY_SECRET, response.getCredentials().getAccessKeySecret());
        jsonObject.put(SECURITY_TOKEN, response.getCredentials().getSecurityToken());
        jsonObject.put(EXPIRATION, response.getCredentials().getExpiration());
        jsonObject.put(USER_ID,userId);
        //叫小林加个时间目录和文件类型
        return jsonObject;
    }
}
